extends Control
class_name Main

@onready var spine: SpineSprite = %SpineSprite
@onready var menu: Container = %Menu
@onready var open_menu: Button = %OpenMenu
@onready var v_slider: VSlider = %VSlider
@onready var time_label: Label = %TimeLabel
@onready var tab_bar: TabBar = %TabBar
@onready var tab_container: PanelContainer = %TabContainer


const LOOT_BUTTON = preload("res://Scenes/loot_button.tscn")

var dragging:bool #拖拽状态
var v2_mouse:Vector2i #鼠标的偏差

var can_move:bool 

# 在类变量区域添加倒计时变量
var countdown_seconds: int = 30 * 60  # 30分钟 = 1800秒
var is_countdown_active: bool = false

# 库存系统
var inventory: Array[SkinState] = []  # 存储所有皮肤状态

func _ready() -> void:
	# 加载设置数据
	load_config()
	# 隐藏菜单
	menu.hide()
	# 加载库存数据
	load_inventory()
	# 设置默认动画
	spine.get_animation_state().set_animation("animation", true, 0)
	# 初始化网格
	var grids = get_tree().get_nodes_in_group("Grids")
	for grid in grids:
		if grid.has_method("init"):
			grid.init()
	# 启动倒计时
	start_countdown()
	# 初始化标签页显示
	_on_tab_bar_tab_changed(0)

# 处理未处理的输入事件
func _unhandled_input(event):
	#键盘Tab   切换button 隐藏/显示
	if event.is_action_pressed("tab"):
		if open_menu.visible==true:
			open_menu.hide()
		else:
			open_menu.show()
	#关闭菜单
	if event.is_action_pressed("exit"):
		menu.hide()
	#初始化设置
	if event.is_action_pressed("init"):
		var window = get_window()
		var screen_size = DisplayServer.screen_get_size()
		var window_size = window.size
		window.position = Vector2i(
			(screen_size.x - window_size.x) / 2,
			(screen_size.y - window_size.y) / 2
		)
		v_slider.value = 5.0
		_on_v_slider_drag_ended(true)

#拖拽窗口
func _input(event):
	if event is InputEventMouseButton and can_move:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			dragging = true
			v2_mouse = get_global_mouse_position()
		else:
			dragging = false
			
	if event is InputEventMouseMotion and dragging and can_move:
		#窗口位置=鼠标位置  - 鼠标的偏差值
		DisplayServer.window_set_position(DisplayServer.mouse_get_position()-v2_mouse)


func _on_mouse_entered() -> void:
	can_move = true
	#print(can_move)

func _on_mouse_exited() -> void:
	can_move = false
	#print(can_move)

func _on_close_menu_pressed() -> void:
	menu.hide()
	open_menu.button_pressed = false


func _on_open_menu_toggled(toggled_on: bool) -> void:
	menu.visible = toggled_on


func _on_exit_pressed() -> void:
	save_inventory()
	save_config()
	get_tree().quit()

func _on_v_slider_drag_ended(value_changed: bool) -> void:
	if value_changed:
		var scale_value = v_slider.value / 10
		spine.scale = Vector2(scale_value, scale_value)


func _on_tab_bar_tab_changed(tab: int) -> void:
	# 获取TabContainer的所有子节点
	var tabs = []
	for i in range(tab_container.get_child_count()):
		var child = tab_container.get_child(i)
		if child is ScrollContainer:  # 确保只处理标签页内容
			tabs.append(child)
	# 隐藏所有标签页
	for t in tabs:
		t.hide()
	# 显示选中的标签页
	if tab >= 0 and tab < tabs.size():
		tabs[tab].show()


#region 半小时开宝箱功能
func show_loot():
	var loot_button = LOOT_BUTTON.instantiate()
	loot_button.position = Vector2(-400,-400)
	loot_button.pressed.connect(_on_loot_button_pressed.bind(loot_button))
	spine.add_child(loot_button)


func _on_loot_button_pressed(button: Button) -> void:
	start_countdown()
	# 移除按钮
	button.disabled = true
	# 随机选择一个皮肤
	var random_skin = get_random_skin()
	if random_skin:
		# 显示提示信息
		var message = "重复获取"
		if not random_skin.is_owned:
			message = "NEW！"
			# 解锁并装备新皮肤
			random_skin.is_owned = true
			# 保存库存数据
			save_inventory()
			# 刷新UI
			update_ui()
		
		var message_label = Label.new()
		message_label.text = message
		message_label.label_settings = time_label.label_settings
		message_label.modulate.a = 1.0
		button.add_child(message_label)
		
		# 创建向上飘动的动画
		var tween = create_tween()
		tween.set_parallel(true)
		# 向上移动
		tween.tween_property(message_label, "position", Vector2(0, -50), 1.0).set_ease(Tween.EASE_OUT)
		# 渐隐效果
		tween.tween_property(message_label, "modulate:a", 0.0, 1.0)
		# 动画完成后删除按钮
		tween.chain().tween_callback(button.queue_free)


# 获取随机皮肤
func get_random_skin() -> SkinState:
	if inventory.size() > 0:
		return inventory[randi() % inventory.size()]
	else:
		return null


# 刷新UI
func update_ui():
	var grids = get_tree().get_nodes_in_group("Grids")
	for grid in grids:
		if grid.has_method("update_all"):
			grid.update_all()

var is_test_mode := OS.has_feature("editor") or OS.is_debug_build()
@export var COUNTDOWN:int = 1 if is_test_mode else 30
# 启动倒计时
func start_countdown() -> void:
	# 初始化倒计时显示
	time_label.text = "%02d:00" % COUNTDOWN
	if not is_countdown_active:
		countdown_seconds = COUNTDOWN * 60
		is_countdown_active = true
		update_countdown_display()
		$Timer.start()  # 确保场景中有一个Timer节点，间隔设为1秒


# 添加更新倒计时显示的函数
func update_countdown_display() -> void:
	@warning_ignore("integer_division")
	var minutes: int = countdown_seconds / 60
	var seconds: int = countdown_seconds % 60
	time_label.text = "%02d:%02d" % [minutes, seconds]


# 修改定时器超时函数
func _on_timer_timeout() -> void:
	if is_countdown_active and countdown_seconds > 0:
		countdown_seconds -= 1
		update_countdown_display()
		
		if countdown_seconds <= 0:
			# 倒计时结束
			is_countdown_active = false
			time_label.text = "00:00"
			$Timer.stop()
			show_loot()  # 显示宝箱
#endregion


#region 保存库存功能
# 将保存文件扩展名改为.json
const SAVE_FILE = "user://inventory.json"  # 保存文件路径

# 引入自动生成的路径列表
const SKIN_PATHS = preload("res://SkinPaths.gd").SKIN_PATHS

func load_inventory() -> void:
	inventory.clear()

	# 加载存档数据
	var saved_data := {}
	if FileAccess.file_exists(SAVE_FILE):
		var file := FileAccess.open(SAVE_FILE, FileAccess.READ)
		if file:
			var json_string := file.get_as_text()
			var json = JSON.parse_string(json_string)
			if typeof(json) == TYPE_ARRAY:
				for item in json:
					var path = item.get("profile_path", "")
					saved_data[path] = {
						"is_owned": item.get("is_owned", false),
						"is_equipped": item.get("is_equipped", false)
					}

	# 从 SKIN_PATHS 加载资源
	for path in SKIN_PATHS:
		if ResourceLoader.exists(path):
			var skin_profile = load(path)
			if skin_profile:
				var skin_state = SkinState.new()
				skin_state.skin_profile = skin_profile
				if saved_data.has(path):
					var data = saved_data[path]
					skin_state.is_owned = data.is_owned
					skin_state.is_equipped = data.is_equipped
				else:
					skin_state.is_owned = false
					skin_state.is_equipped = false
				inventory.append(skin_state)
		else:
			push_warning("皮肤路径无效: " + path)

	# 初始化自定义皮肤
	init_custom_skin()


# 保存库存数据
func save_inventory() -> void:
	var save_data := []
	for state in inventory:
		var item := {
			"profile_path": state.skin_profile.resource_path,
			"is_owned": state.is_owned,
			"is_equipped": state.is_equipped
		}
		save_data.append(item)

	var json_string := JSON.stringify(save_data, "\t")
	var file := FileAccess.open(SAVE_FILE, FileAccess.WRITE)
	if file:
		file.store_string(json_string)
	else:
		push_error("保存库存数据失败：无法写入 " + SAVE_FILE)



# 保存屏幕位置、大小设置
func save_config() -> void:
	var config = ConfigFile.new()
	var window = get_window()
	config.set_value("window", "position", window.position)
	config.set_value("window", "scale", v_slider.value)
	config.save("user://config.cfg")

# 加载屏幕位置、大小设置
func load_config() -> void:
	var config = ConfigFile.new()
	var err = config.load("user://config.cfg")
	if err == OK:
		var window = get_window()
		var saved_position = config.get_value("window", "position", window.position)
		window.position = saved_position
		var saved_scale = config.get_value("window", "scale", 5.0)
		v_slider.value = saved_scale
		_on_v_slider_drag_ended(true)


# 在程序退出时保存数据
func _notification(what: int) -> void:
	if what == NOTIFICATION_WM_CLOSE_REQUEST:
		_on_exit_pressed()
#endregion


var custom_skin:Dictionary = {}

func init_custom_skin():
	# 清空当前的custom_skin
	for key in custom_skin.keys():
		custom_skin[key] = null
	
	# 遍历inventory中的所有皮肤状态
	for skin_state in inventory:
		# 只处理已装备的皮肤
		if skin_state.is_equipped:
			# 获取皮肤类型并更新custom_skin
			var type = skin_state.skin_profile.type
			custom_skin[type] = skin_state
	print(custom_skin)
	update_skin()

func change_skin(type:String,skin_state):
	custom_skin[type] = skin_state
	print(custom_skin)
	update_skin()

func update_skin():
	var skin = spine.new_skin("new-skin")
	var skeleton = spine.get_skeleton()
	var data = skeleton.get_data()
	skin.add_skin(data.find_skin("default"))
	skin.add_skin(data.find_skin("samurai/body/body"))
	skin.add_skin(data.find_skin("nin/body/body"))
	#查找custom_skin中所有非null的值
	var non_null_values = custom_skin.values().filter(func(value) -> bool:
		return value != null
	)
	#遍历non_null_values中的所有皮肤状态
	for skin_state in non_null_values:
		skin.add_skin(data.find_skin(skin_state.skin_profile.address))
	skeleton.set_skin(skin)
	skeleton.set_slots_to_setup_pose()
	spine.get_animation_state().apply(skeleton)
	
